<?php

namespace App\Api\Controllers\Dong_Guan;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class BaseController
{
    //基础url
    public $baseUrl = 'https://qra.95516.com/pay/gateway';

    protected function request_by_curl($remote_server, $post_string)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        // curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        // curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    //推送消息
    protected function send($message)
    {
        $webhook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=d9ed60d3-a4a0-4aee-b335-6b90b8b1a4dc";
        $data = [
            'msgtype' => 'markdown',
            'markdown' => [
                'content' => $message
            ]
        ];
        $data_string = json_encode($data);
        $result = $this->request_by_curl($webhook, $data_string);
        $result = json_decode($result, true);
        if ($result === null && json_last_error() !== JSON_ERROR_NONE) {
            Log::channel('daily')->debug("东莞银行推送消息出错：推送返回数据格式有误");
            return false;
        }
        if ($result['errcode'] != 0) {
            Log::channel('daily')->debug("东莞银行推送消息出错：" . $result['errmsg']);
            return false;
        }
        return true;
    }

    protected function _exception($msg, $code = 0)
    {
        throw new \Exception($msg, $code);
    }

    protected function xml_encode($array)
    {
        $xml = '<xml>';
        foreach ($array as $k => $v) {
            $xml .= '<' . $k . '><![CDATA[' . $v . ']]></' . $k . '>';
        }
        $xml .= '</xml>';
        return $xml;
    }


    protected function xml_decode($content)
    {
        $data = [];
        $encode = '';
        libxml_disable_entity_loader(true);
        $xml = simplexml_load_string($content);
        $preg = preg_match("/<?xml[^>]* encoding=\"(.*)\"[^>]* ?>/i", $content, $arr);
        if ($preg) {
            $encode = strtoupper($arr[1]);
        }
        if ($xml && $xml->children()) {
            foreach ($xml->children() as $node) {
                //有子节点
                if ($node->children()) {
                    $k = $node->getName();
                    $nodeXml = $node->asXML();
                    $v = substr($nodeXml, strlen($k) + 2, strlen($nodeXml) - 2 * strlen($k) - 5);
                } else {
                    $k = $node->getName();
                    $v = (string)$node;
                }

                if ($encode != "" && $encode != "UTF-8") {
                    $k = iconv("UTF-8", $encode, $k);
                    $v = iconv("UTF-8", $encode, $v);
                }

                $data[$k] = $v;
            }
        }
        return $data;
    }

    protected function verification($data)
    {
        $sort = $data;
        $private_key = DB::table('dongguanbank_stores')->where('mch_id', $data['mch_id'])->value('private_key');
        ksort($sort);
        $signature = '';
        foreach ($sort as $k => $v) {
            if ("" != $v && "sign" != $k) {
                $signature .= $k . "=" . $v . "&";
            }
        }
        $signature .= "key=" . $private_key;
        $sign = strtoupper(md5($signature));
        return $sign == $data['sign'];
    }

    protected function curlPost($url, $params, $data, $private_key)
    {
        $sort = $data;
        ksort($sort);
        $signature = '';
        foreach ($sort as $k => $v) {
            if ("" != $v && "sign" != $k) {
                $signature .= $k . "=" . $v . "&";
            }
        }
        $signature .= "key=" . $private_key;
        $sign = strtoupper(md5($signature));
        $data['sign'] = $sign;
        $xml = $this->xml_encode($data);
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_TIMEOUT => 120,
            CURLOPT_URL => $url,
            CURLOPT_HEADER => false,
            //CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $xml,
        ]);
        $curlResponse = curl_exec($curl);
        $curlCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $curlMsg = curl_error($curl);
        curl_close($curl);
        if (!$curlResponse) {
            $this->_exception('curl请求失败：' . $curlMsg);
        }
        return $curlResponse;
    }


}